<!DOCTYPE html>
<html>
<head>
    <title>Chat Page</title>
</head>
<body>
<div id="chatContainer">
    <div id="chatMessages"></div>
    <div id="userInput">
        <input type="text" id="messageInput" placeholder="Enter your message" />
        <button id="sendButton">Send</button>
    </div>
</div>

<script>
    // 页面加载完毕后执行的函数
    window.onload = function() {
        // 获取页面元素
        var chatMessages = document.getElementById('chatMessages');
        var messageInput = document.getElementById('messageInput');
        var sendButton = document.getElementById('sendButton');

        // 发送消息的函数
        function sendMessage() {
            var message = messageInput.value;

            // 发送POST请求到后端
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/chat/chat1', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 获取响应数据
                    var response = JSON.parse(xhr.responseText);
                    var answer = response.data;

                    // 显示回答消息
                    var messageElement = document.createElement('div');
                    messageElement.innerText = 'Bot: ' + answer;
                    chatMessages.appendChild(messageElement);
                }
            };
            xhr.send(JSON.stringify({ message: message }));

            // 清空输入框
            messageInput.value = '';
        }

        // 监听发送按钮的点击事件
        sendButton.addEventListener('click', function() {
            sendMessage();
        });

        // 监听回车键按下事件
        messageInput.addEventListener('keydown', function(event) {
            if (event.keyCode === 13) {
                sendMessage();
            }
        });
    };
</script>
</body>
</html>
